package com.whw.fy.service.impl;

import com.whw.fy.entity.Message;
import com.whw.fy.entity.Parent;
import com.whw.fy.entity.PurchaseCourseRecords;
import com.whw.fy.mapper.ParentMapper;
import com.whw.fy.mapper.PurchaseCourseRecordsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.xml.crypto.Data;

import com.whw.fy.entity.Pay;
import com.whw.fy.mapper.PayMapper;
import com.whw.fy.service.PayService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PayServiceImpl implements PayService {

    @Resource
    private PayMapper payMapper;
    @Resource
    private ParentMapper parentMapper;

    @Resource
    private PurchaseCourseRecordsMapper purchaseCourseRecordsMapper;

    private Logger logger= LoggerFactory.getLogger(getClass());

    @Override
    public Message deleteByPrimaryKey(String payId) {
        return payMapper.deleteByPrimaryKey(payId) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message insert(Pay record) {
        return payMapper.insert(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message insertSelective(Pay record) {
        return payMapper.insertSelective(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message insertInUse(Pay record, int remindTimes) {
        if (addLessonNumber(record,remindTimes)){
            Parent parent = parentMapper.selectByPrimaryKey(record.getParentId());
            if (parent.getChildId() == null){
                parent.setChildId(String.valueOf(record.getStudentId()));
            }
            else {
                String[] childs = parent.getChildId().split(";");
                int flag = 0;
                for(String id : childs){
                    if (id.equals(String.valueOf(record.getStudentId()))){
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0) {
                    parent.setChildId(parent.getChildId()+";"+record.getStudentId());
                }
            }
            parentMapper.updateByPrimaryKey(parent);
            return payMapper.insertSelective(record) > 0 ? Message.success(null) : Message.fail(null);
        }else {
            return Message.fail("添加失败！请联系系统管理员！");
        }
    }


    @Override
    public Message selectByPrimaryKey(String payId) {
        return Message.success(null).add(payMapper.selectByPrimaryKey(payId));
    }

    @Override
    public Message updateByPrimaryKeySelective(Pay record) {
        return payMapper.updateByPrimaryKeySelective(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message updateByPrimaryKey(Pay record) {
        return payMapper.updateByPrimaryKey(record) > 0 ? Message.success(null) : Message.fail(null);
    }

    @Override
    public Message batchInsert(List<Pay> list) {
        return Message.success(null).add(payMapper.batchInsert(list));
    }

    @Override
    public Message selectAll() {
        return Message.success(null).add(payMapper.selectAll());
    }

    @Override
    public Message selectAllByStudentId(Integer studentId) throws ParseException {
        int j =0;
        List<Pay> payList = payMapper.selectAllByStudentId(studentId);
        HashSet<String> Month = new HashSet<String>();
        List<String> ToStringMonth = new LinkedList<>();
        List<String> ToStringMonths = new LinkedList<>();
        List<Map> mapList = new LinkedList<>();
        for (Pay pay:payList){
            if(Month.add(GetMonth(pay.getPayTime()))){
                ToStringMonth.add(GetMonth(pay.getPayTime()));
                ToStringMonths.add(GetMonths(pay.getPayTime()));
            }
        }
        for (String monthss:ToStringMonth) {
            HashMap hashMap = new HashMap();
            hashMap.put("date",monthss);
            List<Pay> payList1 = new LinkedList<>();
            for (int i = 0; i < payList.size(); i++) {
                Pay pay = payList.get(i);
                if (IsThisMonth(pay.getPayTime(), ToStringMonths.get(j))) {
                    payList1.add(pay);
                }
            }
            hashMap.put("payList",payList1);
            mapList.add(hashMap);
            j++;
        }
        return Message.success(null).add(mapList);
    }

    @Override
    public Message selectByParentId(Integer parentId) throws ParseException {
        int j =0;
        List<Pay> payList = payMapper.selectByParentId(parentId);
        HashSet<String> Month = new HashSet<String>();
        List<String> ToStringMonth = new LinkedList<>();
        List<String> ToStringMonths = new LinkedList<>();
        List<Map> mapList = new LinkedList<>();
        for (Pay pay:payList){
            if(Month.add(GetMonth(pay.getPayTime()))){
                ToStringMonth.add(GetMonth(pay.getPayTime()));
                ToStringMonths.add(GetMonths(pay.getPayTime()));
            }
        }
        for (String monthss:ToStringMonth) {
            HashMap hashMap = new HashMap();
            hashMap.put("date",monthss);
            List<Pay> payList1 = new LinkedList<>();
            for (int i = 0; i < payList.size(); i++) {
                Pay pay = payList.get(i);
                if (IsThisMonth(pay.getPayTime(), ToStringMonths.get(j))) {
                    payList1.add(pay);
                }
            }
            hashMap.put("payList",payList1);
            mapList.add(hashMap);
            j++;
        }
        return Message.success(null).add(mapList);
    }

    public boolean addLessonNumber(Pay pay,int remindTimes) {
        PurchaseCourseRecords purchaseCourseRecords = purchaseCourseRecordsMapper.selectByStudentIdAndLessonId(pay.getStudentId(), pay.getLessonId());
        //首次上该门课程
        if (purchaseCourseRecords == null) {
            PurchaseCourseRecords newPurchase = new PurchaseCourseRecords();
            newPurchase.setPayId(pay.getPayId());
            newPurchase.setStudentId(pay.getStudentId());
            newPurchase.setLessonId(pay.getLessonId());
            newPurchase.setPurchaseTimes(pay.getClassHours());
            newPurchase.setClassTimes(0);
            newPurchase.setRemainingTimes(pay.getClassHours());
            newPurchase.setClassStatus(0);
            newPurchase.setRemindTimes(remindTimes);
            newPurchase.setPostTime(new Date());
            if (purchaseCourseRecordsMapper.insertSelective(newPurchase)>0){
                logger.info("学生id"+pay.getStudentId()+"首次上课程"+pay.getLessonId()+"，添加购买课程记录成功！");
                return true;
            }else {
                logger.info("学生id"+pay.getStudentId()+"首次上课程"+pay.getLessonId()+"，添加购买课程记录失败！");
                return false;
            }
        }
        //续费该门课程
        else {
            int GouMaiCiShu = purchaseCourseRecords.getPurchaseTimes()+pay.getClassHours();
            int ShengYuCiShu = purchaseCourseRecords.getRemainingTimes()+pay.getClassHours();
            purchaseCourseRecords.setPurchaseTimes(GouMaiCiShu);
            purchaseCourseRecords.setRemainingTimes(ShengYuCiShu);
            purchaseCourseRecords.setRemindTimes(remindTimes);
            if (purchaseCourseRecords.getClassStatus()==1){
                purchaseCourseRecords.setClassStatus(0);
            }
            if (purchaseCourseRecordsMapper.updateByPrimaryKeySelective(purchaseCourseRecords)>0){
                logger.info("学生id"+pay.getStudentId()+"续费课程"+pay.getLessonId()+"，添加购买课程记录成功！");
                return true;
            }else {
                logger.info("学生id"+pay.getStudentId()+"续费课程"+pay.getLessonId()+"，添加购买课程记录失败！");
                return false;
            }
        }
    }

    public String GetMonth(Date someDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM");
        String nowMonth = simpleDateFormat.format(someDate);
        return nowMonth;
    }

    public String GetMonths(Date someDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYYMM");
        String nowMonth = simpleDateFormat.format(someDate);
        return nowMonth;
    }

    public Boolean IsThisMonth(Date someDate,String someMonth) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYYMM");
        String nowMonth = simpleDateFormat.format(someDate);
        return Integer.parseInt(someMonth) == Integer.parseInt(nowMonth);
    }
}



